<template>
	<view class="container">
		<view class="box">
			<u--image class="img" src="../../../static/logo.png" width="94rpx" height="62rpx"></u--image>
			<view class="title">欢迎使用{{info.AppName}}</view>
			<view class="box-form">
				<u-form ref="uForm" :rules="rules" :model="formdata">
					<u-form-item label-position="top" :borderBottom='false' v-for="(item, index) in inputs" :key="index"
						:label="item.label" :label-width="200" :prop="item.value">
						<view style="display: flex; width: 100%;">
							<u--input style="flex: 1;" shape='circle' clearable
								:maxlength="item.value == 'utel' ? 11 : 6" :prefixIcon='item.icon'
								v-model="formdata[item.value]" :type="item.type" :placeholder='item.placeholder'
								@blur="handleBlur(item.value)" @change="handleChange(item.value)">
								<u--image style="margin-top: 2rpx;" slot="prefix" :src="item.url" width="36rpx"
									height="36rpx"></u--image>
								<template slot="suffix" v-if="item.value === 'utel'" ref="code">
									<wpasssmsbtn :mda="Kaptcha.mda" :res='formdata.res' @refreshCode='refreshCode'
										@again-code='againCode' v-if="item.value == 'utel'" ref="code" @click="getcode">
									</wpasssmsbtn>
								</template>
								<template slot="suffix" v-if="item.value === 'res'">
									<u-image width="175rpx" height="50rpx" :src="Kaptcha.img"
										@click="getWpassSmsAreaKaptcha"></u-image>
									</wpasssmsbtn>
								</template>

							</u--input>
						</view>
					</u-form-item>
					<view class="button-container" style="text-align: center; padding: 96rpx 0;">
						<u-button type="primary" shape="circle" size="medium" @click="updatafn">
							{{ $z.$t('开始充电') }}
						</u-button>
					</view>
				</u-form>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				Kaptcha: {},
				formdata: {
					utel: '',
					yzm: '',
					res: ''
				},
				gtel: '',
				td: 0,
				info: {},
				WpassSmsfalg: false,
				parkingLockType: '',
				rules: {
					utel: [{
							required: true,
							message: this.$z.$t("请输入手机号"),
							trigger: ['blur', 'change'],
						},
						{
							message: "手机号码长度最长11位",
							trigger: ['blur', 'change'],
							validator(rule, value, callback) {
								if (value.length > 11) {
									callback(new Error('error'))
								} else {
									callback()
								}
							},
						},
						{
							message: this.$z.$t("请输入数字"),
							trigger: ['blur', 'change'],
							validator(rule, value, callback) {
								if (!/^\d+$/.test(value)) {
									callback(new Error('error'))
								} else {
									callback()
								}
							},
						}
					],
					res: [{
						required: true,
						message: this.$z.$t("请输入图形验证码"),
						trigger: ['blur', 'change']
					}],
					yzm: [{
						required: true,
						message: this.$z.$t("请输入短信验证码"),
						trigger: ['blur', 'change']
					}],

				}
			}
		},

		computed: {
			inputs() {
				return [{
						url: '../../../static/icon-phone.png',
						placeholder: '请输入手机号',
						value: 'utel'
					},
					{
						value: "res",
						placeholder: "图形验证码",
						url: '../../../static/icon-code.png',
					},
					{
						url: '../../../static/icon-code.png',
						placeholder: '请输入短信验证码',
						value: 'yzm'
					}

				];
			},
			codestr() {
				return this.$refs.code ? this.$refs.code.str : '';
			},
			titmc() {
				return this.$store.state.user.titmc;
			}
		},

		async onLoad(query) {
			const params = query.gtel.split("_");
			this.gtel = params[0];
			this.td = params.length > 1 ? parseInt(params[1]) : 0;
			let info = await this.$z.request("/GetAppinfo");
			this.info = info[0]
			console.log('this.info', this.info)
			this.getWpassSmsAreaKaptcha()
		},
		watch: {
			formdata: {
				handler(newName) {
					let str = newName.utel.replaceAll(' ', '');
					if (str !== newName.utel) {
						newName.utel = str;
					}
				},
				deep: true
			}
		},

		methods: {
			async againCode() {
				this.formdata.yzm = ''
				this.formdata.res = ''
				// this.WpassSmsfalg = false
				await this.getWpassSmsAreaKaptcha()
			},
			async refreshCode() {
				this.formdata.res = ''
				this.getWpassSmsAreaKaptcha()
			},
			async getWpassSmsAreaKaptcha() {
				let Kaptcha = await this.$z.request("/WpassSmsAreaKaptcha");
				Kaptcha.img = "data:image/png;base64," + Kaptcha.img
				this.Kaptcha = Kaptcha
				console.log('this.Kaptcha', this.Kaptcha)
			},
			handleBlur(field) {
				this.$refs.uForm.validateField(field);
			},
			handleChange(field) {
				this.$refs.uForm.validateField(field);
			},
			async getParkingLock() {
				let ChargeCarSys = await this.$z.request("/ChargeCarSys", {
					gtel: this.gtel,
				});
				ChargeCarSys = ChargeCarSys[0]
				this.parkingLockType = ChargeCarSys.type
			},
			async getcode() {
				this.WpassSmsfalg = false;
				if (!this.formdata.utel) {
					this.$u.toast(this.$z.$t("请输入手机号"));
					return;
				}
				const phone = this.formdata.utel.replace(/\s+/g, '');
				if (!this.validatePhoneNumber(phone)) {
					this.$u.toast(this.$z.$t("手机号格式不正确"));
					return;
				}
				if (!this.formdata.res) {
					this.$u.toast(this.$z.$t("请输入图形验证码"));
					return;
				}
				this.$refs.code[0]
					.getCode(this.formdata.utel, "/WpassSmsAreaNoLogin", {
						area: "0",
						mda: this.Kaptcha.mda,
						res: this.formdata.res,
					})
					.then(() => {
						this.formdata.codeutel = this.formdata.utel;
						this.WpassSmsfalg = true;
					})
					.catch(() => {
						this.yzmerr();
					});
			},
			yzmerr() {
				this.getWpassSmsAreaKaptcha();
				this.formdata.res = "";
				this.formdata.yzm = "";
			},
			validatePhoneNumber(phone) {
				const patterns = {
					cn: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
					hk: /^(?:(?:\+|00)852)?[569]\d{7}$/,
					mo: /^(?:(?:\+|00)853)?6\d{7}$/,
					tw: /^(?:(?:\+|00)886)?9\d{8}$/,
					international: /^\+(?:[0-9]●?){4,14}[0-9]$/
				};

				return Object.values(patterns).some(pattern =>
					pattern.test(phone)
				);
			},
			async updatafn() {
				try {
					await this.$refs.uForm.validate();
					console.log('表单校验通过');
				} catch (error) {
					console.log('表单校验失败', error);
					return;
				}

				if (this.formdata.codeutel === '') {
					return;
				}
				try {
					await this.$refs.code[0].codeyz(this.formdata.yzm, this.formdata.utel);

				} catch (error) {
					if (error.message === "INVALID_CODE") {
						// 特殊处理验证码错误
						this.getWpassSmsAreaKaptcha();
					}

				}
				if (!this.$store.state.user.USearch.uUser) {
					await this.$store.dispatch("user/getuser");
				}
				let USearch = this.$store.state.user.USearch;
				USearch.utel = this.formdata.codeutel;
				let par = await this.$z.request('/Uedt', USearch);

				if (par[0].par === 'succeed') {
					this.$u.toast(this.$z.$t("操作成功"));
					await this.getParkingLock()
					if (this.parkingLockType == 14) {
						uni.reLaunch({
							url: `/pages/parkingLock/parkingLock?gtel=${this.gtel}_${this.td}`,
						})
					} else {
						uni.reLaunch({
							url: `/pages/ChargeCarSys/ChargeCarSys?gtel=${this.gtel}_${this.td}`,
						})
					}
				} else {
					this.$u.toast(this.$z.$t("操作失败"));
				}
			}
		}
	}
</script>

<style lang="scss">
	::v-deep .u-form-item__body__right__message {
		margin: 0 !important;
		padding-left: 50rpx !important;
	}

	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx;
	}

	.box {
		width: 100%;
		max-width: 750rpx;
		margin: 0 auto;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
	}

	.img {
		margin-top: 80rpx;
		margin-left: 290rpx;
		margin-bottom: 20rpx;
	}

	.title {
		font-weight: 600;
		text-align: center;
		margin-bottom: 40rpx;
		font-size: 40rpx;
		color: #2093F5;
		line-height: 56rpx;
	}

	.box-form {
		width: 100%;
	}

	.button-container {
		width: 100%;
		display: flex;
		justify-content: center;
	}
</style>